package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now());
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 解决缓存穿透
     * @param id
     * @return
     */
    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                Function<ID,R> dbFallback,Long time,TimeUnit unit){
        //1.从redis查询商铺缓存
        String key =keyPrefix+id;
        //2.判断是否存在
        String json = stringRedisTemplate.opsForValue().get(key);
        //3.存在直接返回
        if (StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json,type);
        }
        //判断命中是否是空值
        if (json != null){
            //返回错误信息
            return null;
        }
        //4.不存在根据id查询数据库
        //使用有参有返回值的函数Function,函数编程
        R r = dbFallback.apply(id);
        //5.不存在返回错误
        if (r == null){
            //将空值写入redis,防止缓存穿透
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //6.存在写入redis
        this.set(key, r ,time,unit);//时间不能写死,所以要获取参数
        return r;
    }

    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        //setIfAbsent如果存在
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);//不能直接返回flag,该包装类在拆箱后会有空指针的问题
    }

    /**
     * 释放锁
     * @param key
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    //因为是热点数据,如果不命中就不是热点数据,所以不用理缓存穿透事件
    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,Class<R> type,
                             Function<ID,R> dbFallback,Long time,TimeUnit unit){
        //1.从redis查询商铺缓存
        String key =keyPrefix+id;
        //2.判断是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //3.存在直接返回
        if (StrUtil.isNotBlank(shopJson)){
            return null;
        }
        //4.命中后需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        //因为我们设定的是Object类型，反序列化时并不知道具体类型
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){
            return r;//未过期直接返回
        }
        //过期重建缓存
        //获取互斥锁
        String lockKey = LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            //注意:获取锁成功应该再次检测redis缓存是否过期，做DoubleCheck。如果存在则无需重建缓存。
            //双重检查目的在于防止获取锁的过程中别的线程完成了缓存重建，而不是等待的过程中
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    R r1 = dbFallback.apply(id);//读取数据库
                    this.setWithLogicalExpire(key,r1,time,unit);//写入redis
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        return r;
    }






















}
